<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <div class="head-container">
          <el-select
            @change="crud.toQuery"
            v-model="query.orderType"
            style="width: 200px;"
            class="filter-item"
            placeholder="请选择订单类型"
            clearable
            filterable
          >
            <el-option v-for="item in dict.order_type" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>

          <rrOperation />
        </div>
      </div>
      <!-- <crudOperation :permission="permission" /> -->
    </div>
    <!--表单组件-->
    <el-dialog
      append-to-body
      :close-on-click-modal="false"
      :before-close="crud.cancelCU"
      :visible.sync="crud.status.cu > 0"
      :title="crud.status.title"
      width="1200px"
    >
      <el-form ref="form" :model="form" :inline="true" :rules="rules" size="small" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="8" :offset="0">
            <el-form-item label="比赛名称" prop="goodsName">
              <el-input v-model="form.goodsName" style="width: 220px;" />
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="0">
            <el-form-item label="目标人群" prop="aimPeople">
              <el-input v-model="form.aimPeople" style="width: 220px;" />
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="0">
            <el-form-item label="联系邮箱" prop="email">
              <el-input v-model="form.email" style="width: 220px;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8" :offset="0">
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker v-model="form.startTime" type="date" placeholder="选择日期时间" style="width: 220px;">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8" :offset="0">
            <el-form-item label="开始时间" prop="endTime">
              <el-date-picker v-model="form.endTime" type="date" placeholder="选择日期时间" style="width: 220px;">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="封面图" prop="coverImage">
          <el-upload
            v-loading="coverImage_loading"
            class="avatar-uploader el-upload"
            action="https://jsonplaceholder.typicode.com/posts/"
            :http-request="(params) => uploadRequest(params, 'coverImage')"
            :show-file-list="false"
          >
            <img v-if="form.coverImage" :src="form.coverImage" class="avatar" />
            <div v-else class="upload-text">选择图片</div>
            <div class="btn" v-if="form.coverImage">
              <el-button size="36" type="text" icon="el-icon-delete" @click.stop="deleteImg('coverImage')"></el-button>
            </div>
          </el-upload>
          <el-input v-show="false" v-model="form.coverImage" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="24" :offset="0">
            <el-form-item label="详情图" prop="detailImage">
              <el-upload
                v-loading="coverImage_loading"
                class="avatar-uploader el-upload"
                v-for="(item, index) in detailList"
                :key="index"
                action="https://jsonplaceholder.typicode.com/posts/"
                :http-request="(params) => uploadDetailRequest(params, 'detailList', 'detailImage')"
                :show-file-list="false"
              >
                <img v-if="item.url" :src="item.url" class="avatar" />
                <div v-else class="upload-text">选择图片</div>
                <div class="btn" v-if="item.url" @click.stop="deleteImg('coverImage')">
                  <el-button size="36" type="text" icon="el-icon-delete"></el-button>
                </div>
              </el-upload>
              <el-upload
                v-loading="coverImage_loading"
                class="avatar-uploader el-upload"
                action="https://jsonplaceholder.typicode.com/posts/"
                :http-request="(params) => uploadDetailRequest(params, 'detailList', 'detailImage')"
                :show-file-list="false"
              >
                <div class="upload-text">选择图片</div>
              </el-upload>
              <el-input v-show="false" v-model="form.detailImage" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="简介" style="width: 100%;">
          <el-input v-model="form.goodsInfo" type="textarea" :rows="4" style="width: 900px;" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="crud.cancelCU">取消</el-button>
        <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
      </div>
    </el-dialog>
    <!--表格渲染-->
    <el-table
      ref="table"
      v-loading="crud.loading"
      :data="crud.data"
      style="width: 100%"
      @selection-change="crud.selectionChangeHandler"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="orderId" label="订单编号" />
      <el-table-column prop="orderType" label="订单类型">
        <template slot-scope="scope">
          <span>{{ selectDictLabel(dict.order_type, scope.row.orderType) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="nickName" label="用户昵称" />
      <el-table-column prop="payStatus" label="支付状态">
        <template slot-scope="scope">
          <el-tag :type="scope.row.payStatus === 1 ? 'success' : 'danger'">{{
            scope.row.payStatus === 1 ? "已支付" : "未支付"
          }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column prop="payTime" label="支付时间" />

      <el-table-column prop="status" label="订单状态">
        <template slot-scope="scope">
          <el-tag :type="orderStatusColor[+scope.row.status]">{{
            selectDictLabel(dict.order_status, scope.row.status)
          }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column v-if="checkPer(['admin', 'serverDeploy:edit', 'serverDeploy:del'])" label="操作" width="200px">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="toDetail(scope.row)">详情</el-button>
          <el-button
            v-if="scope.row.orderType == 3 && scope.row.status == 0"
            type="text"
            size="small"
            @click="toFahuo(scope.row)"
            >文创发货</el-button
          >
          <el-button
            v-if="scope.row.orderType == 2 && scope.row.status != 2"
            type="text"
            size="small"
            @click="toHeyan(scope.row)"
            >师训核验</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!--分页组件-->
    <pagination />
    <el-drawer title="订单详情" append-to-body :visible.sync="detailShow" size="30%">
      <orderDetail v-if="detailShow" :id="detailId" />
    </el-drawer>
    <el-dialog title="文创发货" append-to-body :visible.sync="wcShow" size="20%">
      <el-form ref="datawc" :model="datawc" :rules="rules1" label-width="140px">
        <el-form-item label="快递单号" prop="deliveryId">
          <el-input v-model="datawc.deliveryId"></el-input>
        </el-form-item>
        <el-form-item label="快递类型" prop="deliveryType">
          <el-input v-model="datawc.deliveryType" placeholder="例如：圆通、顺丰"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" @click="wcShow = false">取消</el-button>
        <el-button type="primary" :loading="wcloading" @click="wcSubmit">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import crudMatch from "@/api/mini/match";
import { sendGoods, verificationOrder } from "@/api/mini/order";
import { uploadFile } from "@/api/data";
import CRUD, { presenter, header, form, crud } from "@crud/crud";
import rrOperation from "@crud/RR.operation";
import crudOperation from "@crud/CRUD.operation";
import udOperation from "@crud/UD.operation";
import pagination from "@crud/Pagination";
import orderDetail from "./orderDetailDialog.vue";
const defaultForm = { title: "", type: "", ifShow: "", limitAmount: "", sort: "", coverImage: "", content: "" };
export default {
  name: "Order",
  dicts: ["order_type", "order_status"],
  components: { pagination, crudOperation, rrOperation, udOperation, orderDetail },
  cruds() {
    return CRUD({
      title: "订单",
      props: { searchToggle: true },
      url: "/api/order/orderList",
      listMethod: "post",
      listKey: ["data", "list"],
      totalKey: ["data", "total"],
      crudMethod: { ...crudMatch },
      query: { type: 1 },
    });
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],

  data() {
    return {
      accountList: [],
      accountMap: {},
      loading: false,
      coverImage_loading: false,
      detailList: [],
      bannerList: [],
      dateRange: [],
      permission: {
        edit: ["admin", "proportion:edit"],
      },
      orderStatusColor: {
        0: "primary",
        1: "danger",
        2: "success",
      },
      rules: {
        goodsName: [{ required: true, message: "请输入比赛名称", trigger: "blur" }],
        aimPeople: [{ required: true, message: "请填写目标人群", trigger: "blur" }],
        email: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
        coverImage: [{ required: true, message: "请上传封面图", trigger: "blur" }],
        detailImage: [{ required: true, message: "请上传详情图", trigger: "blur" }],
        endTime: [{ required: true, message: "请选择结束时间", trigger: "blur" }],
        startTime: [{ required: true, message: "请选择开始时间", trigger: "blur" }],
      },
      rules1: {
        deliveryId: [{ required: true, message: "请输入单号", trigger: "blur" }],
        deliveryType: [{ required: true, message: "请填写类型", trigger: "blur" }],
      },
      detailShow: false,
      wcShow: false,
      datawc: {
        deliveryId: "",
        deliveryType: "",
        id: 0,
      },
      wcloading: false,
    };
  },
  mounted() {
    console.log("this.dict :>> ", this.dict);
  },
  methods: {
    toHeyan(row) {
      this.$confirm("确定核验?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          verificationOrder(row.id).then((res) => {
            this.$message.success("核验成功");
            this.crud.toQuery();
          });
        })
        .catch(() => {
          row.status = !status;
        });
    },
    wcSubmit() {
      this.$refs.datawc.validate((valid) => {
        if (valid) {
          this.wcloading = true;
          sendGoods(this.datawc).then((res) => {
            this.wcloading = false;
            this.$message.success("发货成功");
            this.wcShow = false;
            this.crud.toQuery();
          });
        }
      });
    },
    toFahuo(row) {
      this.wcShow = true;
      this.datawc = {
        deliveryId: "",
        deliveryType: "",
        id: row.id,
      };
    },
    toDetail(row) {
      this.detailId = row.id;
      this.detailShow = true;
      // this.$router.push({ name: 'orderDetail', query: { id: row.id } })
    },
    detailImgchange() {
      console.log("this.fileList :>> ", this.fileList);
    },

    uploadRequest(params, key) {
      console.log("params :>> ", params);
      this[`${key}_loading`] = true;
      uploadFile(params).then((res) => {
        console.log("res :>> ", res);
        this[`${key}_loading`] = false;
        this.form[key] = res.data;
        this.$set(this.form, key, res.data);
      });
    },
    uploadDetailRequest(params, listKey, key) {
      uploadFile(params).then((res) => {
        this[listKey].push({ name: params.file.name, url: res.data });
        this.form[key] = this[listKey].map((item) => item.url).join(",");
      });
    },

    deleteImg(key) {
      this.form[key] = "";
    },
    changeStatus(status, row) {
      this.$confirm("确定要修改上架状态吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          crudMatch.changeMatchStatus(row.id).then((res) => {
            this.$message.success("修改成功");
            this.crud.toQuery();
          });
        })
        .catch(() => {
          row.status = !status;
        });
    },

    // 新增编辑前做的操作
    [CRUD.HOOK.beforeToCU](crud, form) {
      this.bannerList = form.showImage ? form.showImage.split(",").map((url) => ({ url })) : [];
      this.detailList = form.detailImage ? form.detailImage.split(",").map((url) => ({ url })) : [];
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .el-input-number .el-input__inner {
  text-align: left;
}

.avatar-uploader,
.el-upload {
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px !important;
  height: 178px;
  display: inline-block;
}

.avatar-uploader:hover,
.el-upload:hover {
  border-color: #409eff;
}

.upload-text {
  font-size: 14px;
  color: #8c939d;
  line-height: 178px;
  text-align: center;
  margin: 0 auto;
}

.avatar {
  width: 178px;
  height: 178px;
  display: inline-block;
  object-fit: cover;
}
.btn {
  display: none;
  position: absolute;
  top: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  width: 178px !important;
  height: 178px;
  border-radius: 0 6px 0 6px;
  text-align: center;
  line-height: 178px;
}

.avatar-uploader:hover {
  // 鼠标悬浮显示按钮
  .btn {
    display: block;
  }
}
</style>
